<?php

namespace App\Http\Middleware;

use App\Models\Log;
use App\Models\Permission;
use Closure;
use Auth;
use Dingo\Api\Routing\Helpers;
use Illuminate\Support\Facades\DB;

class AfterMiddleware
{
    use Helpers;
    //后置中间件
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $name = $request->route()->getName();
        //日志记录
        $permission = Permission::where('name',$name)->first();
        if($permission){
            Log::create([
                'user_id' => Auth::user()->id,
                'ip' => empty(Auth::user()->login_ip)?'':Auth::user()->login_ip,
                'content' =>  $alias = $permission->alias.'操作'
            ]);
        }
        if(!Auth::user()){
            return $response;
        }
        //登陆记录
        if($name == 'api.auth.login'){
            Log::create([
                'user_id' => Auth::user()->id,
                'ip' => empty(Auth::user()->login_ip)?'':Auth::user()->login_ip,
                'content' =>  '登陆操作'
            ]);
        }
        //判断账号是否被禁用
        if(Auth::user()->status != 1){
            return response()->json(['error' => '账号被禁用'], 401);
        }
        return $response;
    }
}
